#include "Sphere.h"
#include "Ray.h"
#include <math.h>

//bool Sphere::Intersect(D3DXVECTOR3 ray)
//{
//	return false;
//}

//float Sphere::Intersect(RAY &ray) 
//{
//	D3DXVECTOR3 dst = ray.origin - this->center;
//	float B = D3DXVec3Dot(&dst, &ray.direction);
//	float C = D3DXVec3Dot(&dst, &dst) - this->radius ;
//	float D = B*B - C;
//	return D > 0.0f ? -B - sqrt(D) :  FLT_MAX;
//}

float Sphere::Intersect(RAY &ray)
{

	RAY tempRay;
	tempRay.direction = ray.direction;
	tempRay.origin = ray.origin - center;

	//Compute A, B and C coefficients
	float a = ::D3DXVec3Dot(&tempRay.direction, &tempRay.direction);
    float b = 2 * D3DXVec3Dot(&tempRay.direction, &tempRay.origin);

	float compRad = radius;
	if(radius < 1.0f){
		compRad= 1.0f;
	}

    float c = D3DXVec3Dot(&tempRay.origin, &tempRay.origin) - (radius*radius*9 );

    //Find discriminant
    float disc = b * b - 4 * a * c;
    
    // if discriminant is negative there are no real roots, so return 
    // false as ray misses sphere
    if (disc < 0)
        return FLT_MAX;

    // compute q as described above
    float distSqrt = sqrtf(disc);
    float q;
    if (b < 0)
        q = (-b - distSqrt)/2.0;
    else
        q = (-b + distSqrt)/2.0;

    // compute t0 and t1
    float t0 = q / a;
    float t1 = c / q;

    // make sure t0 is smaller than t1
    if (t0 > t1)
    {
        // if t0 is bigger than t1 swap them around
        float temp = t0;
        t0 = t1;
        t1 = temp;
    }

    // if t1 is less than zero, the object is in the ray's negative direction
    // and consequently the ray misses the sphere
    if (t1 < 0)
        return FLT_MAX;

    // if t0 is less than zero, the intersection point is at t1
    if (t0 < 0)
    {
        //t = t1;
        return t1;
    }
    // else the intersection point is at t0
    else
    {
        //t = t0;
        return t0;
    }
}
//float Sphere::Intersect(RAY &ray) 
//{
//	float B = 2 * ((ray.direction.x * (ray.origin.x - this->center.x)) + (ray.direction.y * (ray.origin.y - this->center.y)) + (ray.direction.z * (ray.origin.z - this->center.z)));
//	float C = ::pow(ray.origin.x - this->center.x,2.0f) + ::pow(ray.origin.y - this->center.y,2.0f) + ::pow(ray.origin.z - this->center.z,2.0f) - ::pow(this->radius,2.0f);
//	float root = ::pow(B,2.0f) - (4 * C
//	float t = FLT_MAX;s
//	if(root >= 0)
//	{
//		t = (-B + ::sqrt(root))/2.0f;
//	}
//	return t;
//}

void Sphere::Normal(D3DXVECTOR3* output, D3DXVECTOR3 &point)
{
	::D3DXVec3Normalize(output, &(point - this->center)); 
}